package com.calcgpa.util;

import java.io.*;
import java.util.Properties;

public class Property {
	private String PROPERTY_FILE = "c:/windows/system32/calcgpa.properties";
	private Properties property = null;
	
	public Property(){
		property = new Properties();
		
	}
	
	/**
	 * Load data from the property file into the instance of @see Properties
	 * @return if load successful than return true, else return false
	 */
	public boolean load(){
        try {
        	create();
            InputStream in = new BufferedInputStream(new FileInputStream(   
                    PROPERTY_FILE));
            property.load(in);   
            in.close();
            return true;
        } catch (Exception e) {   
            e.printStackTrace();   
            return false;
        }   

	}
	
	/**
	 * Get property by the key. By using the getProperty method of @see Properties
	 * @param key the proerty key
	 * @return the property value
	 */
	public String getProperty(String key){
		return property.getProperty(key);
		
	}
	
	/**
	 * Set property value by the key. But the property file does not save to the disk.
	 * @param key 
	 * @param value
	 */
	public void setProperty(String key, String value){
		property.setProperty(key, value);
		
	}
	
	/**
	 * Save the property to disk.
	 * @return If save successfully than return true, otherwise return false.
	 */
	public boolean save(){
		try {
			create();
			OutputStream fos = new FileOutputStream(PROPERTY_FILE);
			property.store(fos, "Update property file.");
			fos.close();
			return true;
		} catch (IOException e) {
			System.err.println("Visit " + PROPERTY_FILE + " for updating error");
			return false;
		}
	}
	
	/**
	 * Create default property file to the disk.
	 * @throws IOException
	 */
	public void create() throws IOException{
		File file = new File(PROPERTY_FILE);
		if (!file.exists()){
			file.createNewFile();
			property = new Properties();
			property.setProperty("com.calcgpa.isremuser", "false");
			property.setProperty("com.calcgpa.isrempwd", "false");
			property.setProperty("com.calcgpa.ispe", "false");
			property.setProperty("com.calcgpa.username", "");
			property.setProperty("com.calcgpa.password", "");
			OutputStream fos = new FileOutputStream(PROPERTY_FILE);
			property.store(fos, "Create property file.");
			fos.close();
		}
	}
}
